<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use App\Events\QueryEvent;
use Illuminate\Support\Facades\Log;

class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\QueryEvent  $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        $query = $event->sql; // 获取SQL语句
        foreach ($event->bindings as $bind) {
            $query = preg_replace('/\?/', (is_numeric($bind) ? $bind : '\'' . $bind . '\''), $query, 1); // 将SQL中的?替换为实际的值
        }

        if (env("APP_DEBUG")) {
            echo $query."\n";
        }

        $content = "query: {$query} time: {$event->time}ms";
        Log::info('SQL EXEC:', [$content]); 
    }
}
